package com.etc.doctor.service.impl;

import cn.hutool.json.JSONUtil;

import com.etc.common.entity.BasicDoctor;
import com.etc.common.mapper.LogMapper;
import com.etc.common.utils.Result;
import com.etc.common.utils.UUIDUtil;
import com.etc.doctor.mapper.LoginAndRegisterMapper;
import com.etc.doctor.service.LoginAndRegisterService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

import static com.etc.common.utils.RedisConstants.*;


@Service
public class LoginAndRegisterServiceImpl implements LoginAndRegisterService {

    @Autowired
    private LoginAndRegisterMapper loginAndRegisterMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    @Transactional
    public Result register(BasicDoctor doctor) throws JsonProcessingException {
        //查询数据库
        BasicDoctor result = loginAndRegisterMapper.queryDoctorByUserName(doctor.getDocUserName());
        //判断用户名是否存在
        if (result == null) {
            //不存在
            //获取uuid
            String id = UUIDUtil.getUUID();
            //设置医生id
            doctor.setDocId(id);
            //设置医生权限 默认为0
            doctor.setDocLimit(0);
            //新增医生数据
            loginAndRegisterMapper.insert(doctor);
            //将对象手动序列化
            String json = mapper.writeValueAsString(doctor);
            //生成token
            String newToken = UUIDUtil.getUUID();
            //写入redis
            stringRedisTemplate.opsForValue().set(LOGIN_KEY, newToken, LOGIN_KEY_TTL, TimeUnit.HOURS);
            //对象写入redis缓存
            stringRedisTemplate.opsForValue().set(LOGIN_CACHE_DOCTOR, json, LOGIN_CACHE_DOCTOR_TTL, TimeUnit.HOURS);
            //获取uuid
            String uuid = UUIDUtil.getUUID();
            //添加日志到数据库
            logMapper.insert(uuid, id,"注册一个账号：" + doctor.getDocUserName());
            //注册成功
            return Result.ok("注册成功！", newToken);
        }
        //存在，则返回注册失败
        return Result.fail("注册失败！该账号已存在！");
    }

    @Override
    public Result login(String userName, String password, HttpServletRequest request) throws JsonProcessingException {
        //获取token
        String token = (String) request.getHeader("token");
        //判断token是否为空
        if (token != null&&!token.equals("null")) {
            //不为空，则查询redis
            String keyToken = stringRedisTemplate.opsForValue().get(LOGIN_KEY);
            //判断token是否一致
            if (keyToken.equals(token)) {
                //token一致，则更新过期时间12h
                stringRedisTemplate.expire(LOGIN_KEY, LOGIN_KEY_TTL, TimeUnit.HOURS);
                stringRedisTemplate.expire(LOGIN_CACHE_DOCTOR, LOGIN_CACHE_DOCTOR_TTL, TimeUnit.HOURS);
                //从redis中获取医生字符串
                String json = stringRedisTemplate.opsForValue().get(LOGIN_CACHE_DOCTOR);
                //将json手动反序列化
                BasicDoctor doctor = mapper.readValue(json, BasicDoctor.class);
                //获取uuid
                String uuid = UUIDUtil.getUUID();
                //添加日志到数据库
                logMapper.insert(uuid,doctor.getDocId(), "登陆账号：" + userName);
                return Result.ok(doctor, token);
            } else {
                return Result.fail("登录失败！");
            }
        } else {
            //查询数据库
            BasicDoctor doctor = loginAndRegisterMapper.queryDoctor(userName, password);
            //判断对象是否为空
            if (doctor == null) {
                //为空
                return Result.fail("暂无此账号！");
            } else {
                //生成token
                String newToken = UUIDUtil.getUUID();
                //写入redis
                stringRedisTemplate.opsForValue().set(LOGIN_KEY, newToken, LOGIN_KEY_TTL, TimeUnit.HOURS);
                //将对象转化成json
                String json = JSONUtil.toJsonStr(doctor);
                //对象写入redis缓存
                stringRedisTemplate.opsForValue().set(LOGIN_CACHE_DOCTOR, json, LOGIN_CACHE_DOCTOR_TTL, TimeUnit.HOURS);
                //获取uuid
                String uuid = UUIDUtil.getUUID();
                //添加日志到数据库
                logMapper.insert(uuid, doctor.getDocId(),"登陆账号：" + userName);
                return Result.ok(doctor, newToken);
            }
        }
    }

}
